;(function(root){
    //内部函数，合并对象
    var extend = function(){
        var results = {},
            i = 0,
            deep = false,
            length = arguments.length;
        if(typeof arguments[0] === "boolean"){
            i = 1;
            deep = arguments[0];
        }
        while(i<length){
            loop(arguments[i]);
            i++;
        }
        function loop(obj){
            for(let k in obj){
                if(deep && Object.prototype.toString.call(obj[k]) === '[object Object]'){
                    results[k] = extend(true, obj[k]);
                }else{
                    results[k] = obj[k];
                }
            }
        }
        return results;
    }
    
    //默认参数
    var defaults = {
        src: 'data-src',
        selector: '.lazyload',
    }

    var Lazyload = function(options){
        this.settings = extend(defaults, options || {});
        this.images = document.querySelectorAll(this.settings.selector);
        this.observer = null;
        this.init();
    }

    Lazyload.prototype = {
        init: function(){
            if(!root.IntersectionObserver) return this.loadImages();
            this.createObserver();
            for(var i = 0; i < this.images.length; i++){
                this.observer.observe(this.images[i]);
            }
        },
        //创建observer对象
        createObserver: function(){
            var self = this;
            this.observer = new IntersectionObserver(function(entries) {
                for(var i = 0; i < entries.length; i++){
                    if(entries[i].intersectionRatio > 0){
                        var target = entries[i].target;
                        self.loadImage(target);
                    }
                }
            });
        },
        //一次性加载所有图片
        loadImages: function(){
            for(var i = 0; i < this.images.length; i++){
                var this_img = this.images[i];
                var src = this_img.getAttribute(this.settings.src);
                this_img.src = src;
            }
        },
        //加载单张图片
        loadImage: function(target){
            var self = this;
            this.observer.unobserve(target);
            var src = target.getAttribute(self.settings.src);
            target.src = src;
        }
    }
    root.lazyload = function(options){
        new Lazyload(options);
    }
}(window))